<template>
  <el-dialog
    title="提示"
    :visible="dialogVisible"
    width="30%"
    @close="closeDialog"
  >
    <!-- 子组件里写点击x关闭弹窗 -->
    <template #default>
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelDialog">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { addRoleAPI, updataRoleAPI, changeRoleAPI } from '@/api/role'
export default {
  name: 'AddRole',
  props: {
    dialogVisible: {
      type: Boolean
    }
  },
  data() {
    return {
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '名字必填', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述必填', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    closeDialog() {
      //  触发事件在子组件，修改的属性来自父组件  是子传父
      this.$emit('close-dialog')
    },
    // 兜底检验
    confirm() {
      // 兜底校验，拿到当前form实例，调用validate方法
      // 检验通过，调用新增接口
      this.$refs.roleForm.validate(async(valid) => {
        if (valid) {
          if (this.roleForm.id) {
            await changeRoleAPI(this.roleForm)
            this.$message.success('xiugai成功')
          } else {
            await addRoleAPI(this.roleForm)
            // 提示用户，
            this.$message.success('邢增成功')
          }
          // 根性列表，传到父组件，调用更新列表  emit
          this.$emit('update-list')
          // 关闭弹框，
          // this.closeDialog()
          this.$emit('close-dialog')
          // 清空表单
          this.$refs.roleForm.resetFields()
          this.roleForm = {
            name: '',
            description: ''
          }
        }
      })
    },
    cancelDialog() {
      this.closeDialog()
      // 清空表单
      this.$refs.roleForm.resetFields()
      this.roleForm = {
        name: '',
        description: ''
      }
    },
    async getRoleInfo(id) {
      console.log(id)
      // 调用接口获取详情数据 直接通过this.roleForm完成赋值
      const res = await updataRoleAPI(id)
      console.log(res)
      this.roleForm = res
    }
  }
}
</script>

<style scoped>
</style>
